package wxdb.record;

import static java.sql.Types.*;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Set;

import sun.reflect.FieldInfo;
import wxdb.tx.Transaction;

public class Schema implements Serializable{
	
	private HashMap<String, FieldInfo> info;

	public Schema(){
		info = new HashMap<String, FieldInfo>();
	}
	
	public void addStringField(String fldName, int len, boolean isKey){
		addField(fldName, VARCHAR, len, isKey);
	}
	
	public void addIntField(String fldName, boolean isKey){
		addField(fldName, INTEGER, Transaction.getIntSize(), isKey);
	}
	
	public void changeIsKey(String fldName, boolean isKey){
		FieldInfo fi = info.get(fldName);
		fi.isKey = isKey;
		info.remove(fldName);
		info.put(fldName, fi);
	}
	
	private void addField(String fldName, int type, int len, boolean isKey){
		info.put(fldName, new FieldInfo(type, len, isKey));
	}
	
	public int getType(String fldName){
		return info.get(fldName).type;
	}
	
	public int getLen(String fldName){
		return info.get(fldName).len;
	}
	
	public boolean getIsKey(String fldName){
		return info.get(fldName).isKey;
	}
	
	public void add(String fldName, Schema sch){
		int type = sch.getType(fldName);
		int len = sch.getLen(fldName);
		boolean isKey = sch.getIsKey(fldName);
		addField(fldName, type, len, isKey);
	}
	
	public void addAll(Schema sch){
		info.putAll(sch.info);
	}
	
	public Set<String> getFields(){
		return info.keySet();
	}
	
	public boolean hasField(String fldName){
		return getFields().contains(fldName);
	}
	
	
	class FieldInfo implements Serializable{
		int type;
		int len;
		boolean isKey;
		public FieldInfo(int type, int len, boolean isKey){
			this.type = type;
			this.len = len;
			this.isKey = isKey;
		}
	}
}
